package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST;
import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //从redis中查询店铺类型
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(SHOP_TYPE_LIST,0,-1);
        //如果存在，直接返回
        if(!shopTypeList.isEmpty()){
            List<ShopType> shoplist = new ArrayList<>();
            for(String s: shopTypeList){
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                shoplist.add(shopType);
            }
            return Result.ok(shoplist);
        }
        //从数据库中查找
        List<ShopType> shoplist = lambdaQuery().orderByAsc(ShopType::getSort).list();
        if(shoplist == null){
            return Result.fail("店铺类型不存在");
        }
        //数据写入到redis中
        for(ShopType shopType: shoplist){
            String jsonStr = JSONUtil.toJsonStr(shopType);
            shopTypeList.add(jsonStr);
        }
        stringRedisTemplate.opsForList().leftPushAll(SHOP_TYPE_LIST,shopTypeList);
        return Result.ok(shoplist);
    }
}
